<script setup>
import { ref, onMounted, watch } from 'vue'
import { Minus, Plus } from '@element-plus/icons-vue'
import { getApplyList } from '@/api/apply'
import { getStreetList } from '@/api/street'
import { submitApproval } from '../../api/apply'
import { ElMessage } from 'element-plus'
import MapShow from '@/components/MapShow.vue'
import { MapLocation } from '@element-plus/icons-vue'

const doorplates = ref([])
const applies = ref([])
const streets = ref([])
const form = ref({
  streetIds: [],
  pageNo: 1,
  pageSize: 10
})
const _res = ref(0)
const activeRowId = ref()
const comment = ref('')
const dialogVisible = ref(false)
const mapDialogVisible = ref(false)

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const checkAll = ref(false)
const indeterminate = ref(false)

const selectAll = (val) => {
  // 把所有街道 id 填进去
  indeterminate.value = false
  if (val) {
    form.value.streetIds = streets.value.map(s => s.id)
  } else {
    form.value.streetIds = []
  }
}


const getStreets = () => {
  getStreetList().then((res) => {
    if (res.code === 0) {
      streets.value = res.data.records
    } else {
      ElMessage.error(res.msg)
    }
  }).catch((error) => {
    console.error(error)
    ElMessage.error('获取街道列表失败')
  })
}

const getApplies = (data) => {
  getApplyList(data).then((res) => {
    applies.value = res.data.records;
    total.value = res.data.total;
    currentPage.value = res.data.current;
    pageSize.value = res.data.size;
  }).catch((err) => {
  })
}

const openApproveDialog = (row, result) => {
  activeRowId.value = row.id        // 保存 applyId
  _res.value = result               // 保存动作
  comment.value = ''                // 清空输入
  dialogVisible.value = true
}

const submitApprove = async () => {
  const id = activeRowId.value
  const data = {
    result: _res.value,
    comment: comment.value
  }
  try {
    await submitApproval(id, data)
    ElMessage.success(data.result === 0 ? '已通过' : '已拒绝')
    dialogVisible.value = false
    getApplies(form.value)
  } catch (e) {
    console.error(e)
    ElMessage.error('操作失败')
  }
}

const showMap = (lng, lat) => {
  mapDialogVisible.value = true
  // 打开地图组件
  doorplates.value = [{ lng, lat, seq: 1 }]
}

getStreets()

const PageSizeChange = (value) => {
  form.value.pageNo = 1 // 重置页码为1
  form.value.pageSize = value
  getApplies(form.value)
}
const PageCurrentChange = (value) => {
  form.value.pageNo = value
  getApplies(form.value)
}

watch(
  () => form.value.streetIds,
  (val) => {
    const len = val.length
    const total = streets.value.length

    checkAll.value = len === total
    indeterminate.value = len > 0 && len < total
  }
)


onMounted(() => {

})
</script>

<template>
  <div>
    <el-form :model="form" label-width="auto">
      <el-form-item label="街道">
        <el-select v-model="form.streetIds" multiple placeholder="选择街道" style="max-width: 90%" collapse-tags
          collapse-tags-tooltip>
          <template #header>
            <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="selectAll">
              全选
            </el-checkbox>
          </template>
          <el-option v-for="street in streets" :key="street.id" :label="street.name" :value="street.id" />
        </el-select>
        <el-button type="primary" @click="getApplies(form)" style="margin-left: 3vmin"
          :disabled="!form.streetIds.length">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="applies" style="width: 100%">
      <el-table-column label="行政区划" prop="divisionName" />
      <el-table-column label="街道" prop="streetName" />
      <el-table-column label="详细位置">
        <template #default="{ row }">
          <el-button type="primary" plain @click="showMap(row.lng, row.lat)" size="small" :icon="MapLocation">
            查看地图
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="门牌号" prop="code" />
      <el-table-column label="类别" prop="clazzName" />
      <el-table-column label="申请进度">
        <template #default="{ row }">
          <el-progress :percentage="row.currentLevel * 100 / row.levels"
            :format="() => `${row.currentLevel}/${row.levels}`" />
        </template>
      </el-table-column>
      <el-table-column label="申请时间" prop="gmtCreated" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="success" plain size="small" @click="openApproveDialog(row, 0)">
            通过
          </el-button>
          <el-button type="danger" plain size="small" @click="openApproveDialog(row, 1)">
            拒绝
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 2vmin">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[1, 2, 5, 10]"
        :background="true" layout="total, sizes, prev, pager, next, jumper" @size-change="PageSizeChange"
        @current-change="PageCurrentChange" :total="total" />
    </div>

    <!-- 审批弹窗（通过 / 拒绝共用） -->
    <el-dialog v-model="dialogVisible" :title="_res === 0 ? '审批意见（通过）' : '审批意见（拒绝）'" width="30%" destroy-on-close>
      <!-- 审批意见 -->
      <el-input v-model="comment" type="textarea" rows="4" placeholder="请输入审批意见" maxlength="255" show-word-limit />

      <!-- footer 按钮 -->
      <template #footer>
        <el-button type="primary" @click="submitApprove">
          提交
        </el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="mapDialogVisible" title="地图" width="500" :before-close="handleClose">
      <map-show v-if="mapDialogVisible" :zoom="10"
        style="width: 100%; height: 400px; border: 1px solid #dcdfe6; border-radius: 4px" :doorplates="doorplates" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="mapDialogVisible = false">返回</el-button>
        </div>
      </template>

    </el-dialog>
  </div>
</template>

<style scoped lang="scss"></style>